<template>
  <div class="p-2">
    <transition>
      <!-- 查询区 -->
      <div class="search" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <!-- <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="暂无数据"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item> -->
          <!-- <el-form-item label="手机号" prop="phoneNumber">
              <el-input
                v-model="queryParams.phoneNumber"
                placeholder="请输入手机号"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item> -->

          <el-form-item label="机构查询" prop="organizationArr">
            <el-cascader
              :props="organizationCascaderProps"
              :show-all-levels="true"
              v-model="queryParams.sourceId"
              :options="organizationTree"
              @change="handleSearchOrganizationChange"
            >
              <template #default="{ node }">
                <span>{{ node.label }}</span>
              </template>
            </el-cascader>
          </el-form-item>

          <el-form-item label="处理状态" prop="status">
            <el-select
              v-model="queryParams.status"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in statusArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="机构查询" prop="organizationArr">
              <el-cascader
                clearable
                :props="organizationCascaderProps"
                :options="searchData.searchOrganizationTree"
                :show-all-levels="false"
                @change="handleSearchOrganizationChange"
              >
                <template #default="{ node }">
                  <span>{{ node.label }}</span>
                </template>
              </el-cascader>
            </el-form-item> -->

          <!-- <el-form-item label="年级" prop="status">
              <el-select
                v-model="queryParams.status"
                clearable
                placeholder="请先选择机构"
              >
                <el-option
                  v-for="item in statusArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="班级" prop="memberStatus">
              <el-select
                v-model="queryParams.memberStatus"
                clearable
                placeholder="请先选择年级"
              >
                <el-option
                  v-for="item in selectArr.memberStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item> -->

          <!-- <el-form-item label="区域查询">
               <el-cascader
                :options="searchData.searchRegionTree"
                clearable
                :props="DialogData.treeProps"
                :show-all-levels="false"
                @change="handleRegionChange"
              >
                <template #default="{ node }">
                  <span>{{ node.label }}</span>
                </template>
              </el-cascader>
            </el-form-item>  -->

          <!-- <el-form-item label="操作时间" prop="timeRange">
              <el-date-picker
                v-model="queryParams.timeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                @change="handleDateRangeChange"
              />
            </el-form-item> -->

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">
              搜索
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
          <el-form-item prop="timeRange">
            <el-button
              v-hasPermi="['sys:organization:query']"
              type="primary"
              size="small"
              :disabled="currentOrganizationId && currentOrganizationId === ''"
              @click="handleGetOrganizationDetail"
            >
              获取邀请码
            </el-button>
            <span>{{ invitationCode }}</span>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <!-- 按钮区 -->
    <el-card shadow="never">
      <!-- 列表区 -->
      <el-table
        v-loading="loading"
        :data="clientUserRequestList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column
          label="手机号"
          align="center"
          prop="initiatorUser.phoneNumber"
        />
        <el-table-column
          label="用户昵称"
          align="center"
          prop="initiatorUser.nickName"
          v-if="true"
        />
        <!--        <el-table-column label="申请" align="center" prop="organization.fullName" />-->
        <el-table-column label="申请时间" align="center" prop="updateTime" />
        <el-table-column
          label="状态"
          align="center"
          prop="examineStatusCodeMsg"
        />
        <!-- <el-table-column
          label="注册方式"
          align="center"
          prop="registrationMethodMsg"
        />
        <el-table-column
          label="最后在线时间"
          align="center"
          prop="lastOnlineTime"
        />
        <el-table-column
          label="累计活跃天数"
          align="center"
          prop="activityDays"
        />
        <el-table-column label="关联孩子数" align="center" prop="childNum" />
        <el-table-column
          label="是否会员"
          align="center"
          prop="memberStatusMsg"
        />
         <el-table-column label="笔记" align="center" prop="nickName" />
          <el-table-column label="评价" align="center" prop="nickName" />
          <el-table-column label="评论" align="center" prop="nickName" /> -->
        <!-- <el-table-column label="状态" align="center" prop="status">
          <template #default="{ row }: { row: ClientUserVo }">
            <el-tag :type="UserStatusTypeMap.get(row.status ?? '') ?? 'info'">
              {{ row.statusMsg }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="禁言" align="center" prop="mutedStatus">
          <template #default="{ row }: { row: ClientUserVo }">
            <el-tag
              :type="MutedStatusTypeMap.get(row.mutedStatus ?? '') ?? 'info'"
            >
              {{ row.mutedStatus === "0" ? "未禁言" : "禁言" ?? "未知" }}
            </el-tag>
          </template>
        </el-table-column>  -->
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-tooltip content="详情" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="FolderOpened"
                @click="handleDetail(scope.row)"
              ></el-button>
            </el-tooltip>
            <!-- 仅对未处理的申请展示处理按钮 -->
            <template v-if="scope.row.status == '0'">
              <span v-hasPermi="['system:organization:join']" class="ml-10px">
                <el-tooltip
                  content="同意申请"
                  placement="top"
                  :enterable="false"
                >
                  <el-button
                    link
                    type="primary"
                    icon="Select"
                    @click="handleAgree(scope.row)"
                    :disabled="scope.row.actionDisabled"
                  ></el-button>
                </el-tooltip>
              </span>
              <span v-hasPermi="['system:organization:join']" class="ml-10px">
                <el-tooltip
                  content="拒绝申请"
                  placement="top"
                  :enterable="false"
                >
                  <el-button
                    link
                    type="primary"
                    icon="CloseBold"
                    @click="handleDisagree(scope.row)"
                    :disabled="scope.row.actionDisabled"
                  ></el-button>
                </el-tooltip>
              </span>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getJoinClassRequestList"
      />
    </el-card>

    <!-- 弹出框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="80%"
      center
      :show-close="false"
      :close-on-click-modal="false"
      @close="handleCloseDialog"
    >
      <el-form
        v-loading="dialogLoading"
        :model="currentDialogData"
        ref="dialogFormRef"
        :rules="rules"
        :inline="true"
        label-width="98px"
        class="dialogForm"
      >
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="用户昵称" prop="nickName">
              <div class="flex">
                <el-input
                  :disabled="dialogData.isDisabled"
                  v-model="dialogData.currentDialogData.initiatorUser.nickName"
                  placeholder="无"
                  clearable
                />
                <!-- <el-button
                    v-else
                    size="small"
                    type="primary"
                    link
                    @click="handleConfirm"
                  >
                    确定
                  </el-button> -->
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号" prop="phoneNumber">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="dialogData.currentDialogData.initiatorUser.phoneNumber"
                placeholder="无"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <!-- <el-col :span="8">
              <el-form-item label="养育类型" prop="parentingMsg">
                <el-input
                  :disabled="dialogData.isDisabled"
                  v-model="currentDialogData.parentingMsg"
                  placeholder="暂无数据"
                  clearable
                />
              </el-form-item>
            </el-col> -->
          <!-- <el-col :span="8">
              <el-form-item label="协助抚养" prop="createTime">
                <el-input
                  :disabled="dialogData.isDisabled"
                  v-model="currentDialogData.createTime"
                  placeholder="无"
                  clearable
                />
              </el-form-item>
            </el-col> -->
        </el-row>

        <el-row :gutter="10">
          <el-form-item label="申请孩子">
            <el-scrollbar style="width: 100%; height: 30vh; overflow-x: auto">
              <div
                class="scrollbar-flex-content"
                v-if="dialogData.currentDialogData.child != undefined"
              >
                <!-- <el-card
                    class="box-card mr-5 scrollbar-demo-item w200px h150px"
                    v-for="(item, index) in currentDialogData.children"
                    :key="index"
                  >
                    <div>
                      <div>姓名：{{ item.name }}</div>
                      <div v-if="item.directOrg">组织：{{ item.directOrg.name }}</div>
                      <div v-else>组织：暂无数据</div>

                      <div v-if="item.grade">年级：{{ item.grade.name }}</div>
                      <div v-else>年级：暂无数据</div>
                    </div>
                  </el-card> -->
                <el-card class="box-card mr-5 scrollbar-demo-item">
                  <!--                  v-for="(item, index) in dialogData.currentDialogData.children"-->
                  <!--                  :key="index"-->
                  <div>
                    <div>
                      姓名：{{ dialogData.currentDialogData.child.name }}
                    </div>
                    <div class="flex">
                      <div>
                        昵称：{{ dialogData.currentDialogData.child.nickName }}
                      </div>
                      <!--                      <el-button-->
                      <!--                        size="small"-->
                      <!--                        type="primary"-->
                      <!--                        link-->
                      <!--                        @click="handleResetChildName(item.id)"-->
                      <!--                      >-->
                      <!--                        重置-->
                      <!--                      </el-button>-->
                    </div>
                    <div>
                      生日：{{
                        useDateFormat(
                          dialogData.currentDialogData.child.birthday,
                          "YYYY-MM-DD",
                        ).value
                      }}
                    </div>
                    <!--                    <div v-if="item.orgList && item.schoolName">-->
                    <!--                      组织：{{ dialogData.currentDialogData.child.schoolName }}-->
                    <!--                    </div>-->
                    <!--                    <div v-else>组织：暂无数据</div>-->

                    <!--                    <div v-if="item.orgList && item.gradeName">-->
                    <!--                      年级：{{ dialogData.currentDialogData.child.gradeName }}-->
                    <!--                    </div>-->
                    <!--                    <div v-else>年级：暂无数据</div>-->

                    <!--                    <div v-if="item.orgList && item.className">-->
                    <!--                      班级：{{ dialogData.currentDialogData.child.className }}-->
                    <!--                    </div>-->
                    <!--                    <div v-else>班级：暂无数据</div>-->
                  </div>
                </el-card>
              </div>
              <!-- <el-empty v-else description="暂无数据" /> -->
              <div v-else>暂无数据</div>
            </el-scrollbar>
          </el-form-item>
        </el-row>

        <!-- <el-form-item label="邮箱" prop="email">
            <el-input
              :disabled="dialogData.isDisabled"
              v-model="currentDialogData.email"
              placeholder="请输入邮箱"
              clearable
            />
          </el-form-item> -->

        <!-- <el-form-item label="性别" prop="sex">
            <el-select
              :disabled="dialogData.isDisabled"
              v-model="currentDialogData.sex"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in selectArr.sexArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item> -->

        <!-- <el-form-item label="机构" prop="organizationArr">
            <el-cascader
              v-model="currentDialogData.organizationId"
              clearable
              :props="DialogData.treeProps"
              :options="searchData.searchOrganizationTree"
              :show-all-levels="false"
              @change="dialogOrganizationChange"
            >
              <template #default="{ node }">
                <span>{{ node.label }}</span>
              </template>
            </el-cascader>
          </el-form-item> -->

        <el-form-item class="dialogFooter">
          <el-button type="primary" icon="Search" @click="addSubmit">
            提交
          </el-button>
          <el-button icon="Refresh" @click="dialog.visible = false">
            关闭
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 移出班级 -->
    <!--    <el-dialog-->
    <!--      v-model="dialog.isRemove"-->
    <!--      title="选择移出班级"-->
    <!--      width="60%"-->
    <!--      center-->
    <!--      :show-close="true"-->
    <!--      :close-on-click-modal="true"-->
    <!--      @close="handleCloseRemoveDialog"-->
    <!--    >-->
    <!--      <el-table v-loading="removeLoading" :data="currentChildList">-->
    <!--        <el-table-column label="孩子姓名" align="center" prop="name" />-->
    <!--        <el-table-column-->
    <!--          label="孩子昵称"-->
    <!--          align="center"-->
    <!--          prop="nickName"-->
    <!--          v-if="true"-->
    <!--        />-->
    <!--        <el-table-column label="学校" align="center" prop="schoolName" />-->

    <!--        <el-table-column label="年级" align="center" prop="gradeName" />-->
    <!--        <el-table-column label="班级" align="center" prop="className" />-->
    <!--        <el-table-column-->
    <!--          label="操作"-->
    <!--          align="center"-->
    <!--          class-name="small-padding fixed-width"-->
    <!--        >-->
    <!--          <template #default="scope">-->
    <!--            <el-tooltip content="移出" placement="top" :enterable="false">-->
    <!--              <el-button link type="primary" @click="removeChild(scope.row.id)">-->
    <!--                <template #icon>-->
    <!--                  <icon-ic-baseline-remove-circle-outline />-->
    <!--                </template>-->
    <!--              </el-button>-->
    <!--            </el-tooltip>-->
    <!--          </template>-->
    <!--        </el-table-column>-->
    <!--      </el-table>-->
    <!--    </el-dialog>-->
  </div>
</template>

<script setup lang="ts">
import {
  getJoinClassRequestList as getJoinClassRequestListApi,
  createClientUser as createClientUserApi,
  getClientUserDetail as getClientUserDetailApi,
  updateClientUser as updateClientUserApi,
  getEvaluateList as getEvaluateListApi,
  getCommentList as getCommentListApi,
  getDiaryList as getDiaryListApi,
  getNotesList as getNotesListApi,
  resetName as resetNameApi,
  resetChildName as resetChildNameApi,
  getOrganizationTree as getOrganizationTreeApi,
  handleHide as handleHideApi,
  handleCommentHide as handleCommentHideApi,
  deleteEvaluate as deleteEvaluateApi,
  deleteComment as deleteCommentApi,
  deleteDiary as deleteDiaryApi,
  deleteNotes as deleteNotesApi,
  agree as agreeApi,
  disagree as disagreeApi,
  getOrganizationDetail as getOrganizationDetailApi,
} from "@/service/api/system/userRequest";
import { useDateFormat } from "@vueuse/core";
import { ElForm } from "element-plus";
import { ref } from "vue";
import Pagination from "@/components/Pagination/index.vue";
import {
  ClientUserInfoVo,
  ClientUserVo,
  OrganizationNode,
  SysExamineTaskVo,
} from "@/service/api/system/frontUser/types.ts";
import { BasePageResponse } from "@/service/api/type.ts";
import { to } from "await-to-js";
import type { TabsPaneContext } from "element-plus";
import { JoinClassProcessResultMap } from "@/maps/frontUser/joinClassRequest/joinClassProcessResult.ts";

type SysExamineTaskVoWithExtra = SysExamineTaskVo & {
  actionDisabled?: boolean;
  examineStatusCodeMsg?: string;
};

// 列表数据s
const clientUserRequestList = ref<SysExamineTaskVoWithExtra[]>([]);

const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref(ElForm);
const dialogFormRef = ref(ElForm);

const dialog = reactive({
  visible: false,
  title: "",
  isSendWarning: false,
  isBan: false,
  isRemove: false,
});

// 获取用户列表BO
const initGetRequestList = {
  pageNum: 1,
  pageSize: 10,
  phoneNumber: "",
  status: "0",
  regionId: "",
  sourceId: "",
  memberStatus: "",
  orderByColumn: "createTime",
  orderType: "desc",
};

// 初始新增用户数据
const initAddUserBO: SysExamineTaskVoWithExtra = {
  // userName: "",
  // email: "",
  // nickName: "",
  // status: "",
  // phoneNumber: "",
  // password: "",
  // sex: "",
  // memberStatus: "",
};

const organizationCascaderProps = {
  // checkStrictly: true,
  value: "id",
  expandTrigger: "hover" as const,
};

// 所有状态
const statusArr = reactive([
  {
    value: "0",
    label: "未处理",
  },
  {
    value: "1",
    label: "已处理",
  },
]);

// 获取用户评价
const initGetUserEvaluateParams = {
  userId: "",
  pageSize: 5,
  pageNum: 1,
};

// 获取用户评论
const initGetCommentParams = {
  userId: "",
  pageSize: 5,
  pageNum: 1,
};

// 获取用户日记
const initGetDiaryParams = {
  userId: "",
  pageSize: 5,
  pageNum: 1,
};

// 获取用户笔记
const initGetNotesParams = {
  userId: "",
  pageSize: 5,
  pageNum: 1,
};

const initGetOrganizationTree = {
  name: "",
  type: "1",
  parentId: 0,
  orderByColumn: "createTime",
  orderType: "desc",
  pageSize: 10,
  pageNum: 1,
};

// 参数，上方查询的数据
const searchData = reactive({
  queryParams: {
    ...initGetRequestList,
  },
  getOrganizationTreeBO: { ...initGetOrganizationTree },
  // 获取组织参数
  organizationParams: {
    pageSize: 10,
    pageNum: 1,
    name: "",
  },
  organizationArr: [],
  status: "0",
  rules: {
    phoneNumber: [{ required: true, message: "手机不能为空", trigger: "blur" }],
    userName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    age: [{ required: true, message: "年龄不能为空", trigger: "blur" }],
    eMail: [{ required: true, message: "邮箱不能为空", trigger: "blur" }],
    status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
    password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
    warningMsg: [
      { required: true, message: "警告信息不能为空", trigger: "blur" },
    ],
  },
  searchRegionTree: [],
  searchOrganizationTree: [],
});

// dialog数据
const dialogData = reactive({
  currentDialogData: {
    ...initAddUserBO,
  },
  getUserEvaluateParams: { ...initGetUserEvaluateParams },
  getCommentParams: { ...initGetCommentParams },
  getDiaryParams: { ...initGetDiaryParams },
  getNotesParams: { ...initGetNotesParams },
  isDisabled: false,
  treeProps: {
    checkStrictly: true,
    value: "id",
  },
});

const { queryParams, rules, getOrganizationTreeBO } = toRefs(searchData);
const {
  currentDialogData,
  getUserEvaluateParams,
  getCommentParams,
  getDiaryParams,
  getNotesParams,
} = toRefs(dialogData);

const organizationTree = ref<any>([]);
/**
 * 获取组织树
 */
const getOrganizationTree = async () => {
  const [err, res] = await to<BasePageResponse<OrganizationNode>, any>(
    getOrganizationTreeApi(getOrganizationTreeBO.value),
  );
  if (!err) {
    console.log(res);
    organizationTree.value = res?.rows ?? [];
    // 获取第一项id
    const firstItem = getFirstChildOfFirstTree(organizationTree.value);
    console.log(firstItem);
    currentOrganizationId.value = firstItem.id;
    queryParams.value.sourceId = currentOrganizationId.value;
    await getJoinClassRequestList();
  }
};
// 获取树形结构数组的第一个节点
const getFirstChildOfFirstTree = (treeArray: Array<any>) => {
  // 递归查找第一个非空元素
  const findFirstNonEmptyElement = (array: any): any => {
    for (let i = 0; i < array.length; i++) {
      if (array[i].children && array[i].children.length > 0) {
        return array[i];
      } else if (array[i].children) {
        return findFirstNonEmptyElement(array[i].children);
      }
    }
    return null;
  };

  // 递归查找第一个子节点的第一个子节点
  const findFirstChild = (element: any): any => {
    if (element.children && element.children.length > 0) {
      return element.children[0];
    } else if (element.children) {
      return findFirstChild(element.children[0]);
    } else {
      return null;
    }
  };

  // 找到第一个非空元素
  let firstNonEmptyElement = findFirstNonEmptyElement(treeArray);

  // 找到第一个非空元素的第一个子节点
  let firstChild = findFirstChild(firstNonEmptyElement);

  return firstChild;
};

/**
 * 获得审核加入列表
 */
const getJoinClassRequestList = async (): Promise<boolean> => {
  loading.value = true;
  queryParams.value.sourceId = currentOrganizationId.value;
  console.log(queryParams.value);
  const [err, res] = await to<BasePageResponse<SysExamineTaskVo>, any>(
    getJoinClassRequestListApi(queryParams.value),
  );
  console.log(res);

  if (!err) {
    total.value = Number(res?.total ?? 0);
    clientUserRequestList.value = res?.rows ?? [];
    clientUserRequestList.value.forEach((item: SysExamineTaskVoWithExtra) => {
      item.actionDisabled = false;
      item.examineStatusCodeMsg =
        JoinClassProcessResultMap.get(item.examineStatusCode ?? -1) ?? "未知";
    });
    loading.value = false;
    return true;
  }

  loading.value = false;
  return false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  console.log(queryParams.value);
  queryParams.value.pageNum = 1;
  getJoinClassRequestList();
};

const currentOrganizationId = ref("");
const invitationCode = ref("");
/**
 * 获取要查询的组织id
 * @param selectedData
 */
const handleSearchOrganizationChange = async (selectedData: any) => {
  console.log(selectedData);
  invitationCode.value = "";
  if (selectedData && selectedData.length > 0) {
    // queryParams.value.organizationId = selectedData[selectedData.length - 1];
    currentOrganizationId.value = selectedData[selectedData.length - 1];
  }
  console.log(queryParams.value.organizationId);
};

// 获取组织详情邀请码
const handleGetOrganizationDetail = async () => {
  const [err, res] = await to(
    getOrganizationDetailApi(currentOrganizationId.value),
  );
  if (!err) {
    console.log(res);
    invitationCode.value = res.data.invitationCode;
  }
};

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.value.timeRange = "";
  queryParams.value.organizationId = "";
  currentOrganizationId.value = "";
  invitationCode.value = "";
  queryParams.value.params = {
    beginTime: <string | null>null,
    endTime: <string | null>null,
  };
  handleQuery();
};

/**
 * 获取多选框选中数据
 */
const handleSelectionChange = (selection: ClientUserVo[]) => {
  ids.value = selection.map((item) => item.id ?? "").filter((id) => id === "");
  // console.log('ID:!!!', ids.value[0])
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  // console.log(single.value, multiple.value)
};

/**
 * dialog中的关闭按钮
 */
const handleCloseDialog = () => {
  currentDialogData.value = Object.assign({}, initAddUserBO);
  dialog.title = "";
  loading.value = false;
  dialogData.isDisabled = false;
  activeName.value = "1";
  commentList.value = [];
  evaluateList.value = [];
};

const currentUserId = ref("");

/**
 * 处理查看用户详情
 * @param row
 */
const handleDetail = async (row: SysExamineTaskVoWithExtra) => {
  loading.value = true;
  dialog.title = "用户详情";
  dialogData.isDisabled = true;

  dialogData.currentDialogData = row;

  // currentUserId.value = row.initiatorId ?? currentUserId.value;
  // const [err, res] = await to<BaseResponse<ClientUserInfoVo>, any>(
  //   getClientUserDetailApi(row.userId ? row.userId : currentUserId.value),
  // );
  //
  // if (!err) {
  //   console.log(res?.data, dialogData.currentDialogData);
  //   if (res?.data) {
  //     dialogData.currentDialogData = res?.data;
  //
  //     if (res?.data?.characterList && res?.data?.characterList.length > 0) {
  //       // 家庭角色
  //       const familyCharacterType = res.data.characterList.filter(
  //         (item) => item.type === "1",
  //       )[0];
  //       // 家长行业
  //       const parentIndustryType = res.data.characterList.filter(
  //         (item) => item.type === "4",
  //       )[0];
  //       // 家长学历
  //       const parentalEducationType = res.data.characterList.filter(
  //         (item) => item.type === "3",
  //       )[0];
  //       // // 家长年龄
  //       // const parentalAgeType = res.data.ageId.filter(
  //       //   (item) => item.type === "2",
  //       // )[0].id;
  //       // 孩子数量
  //       const childNumType = res.data.characterList.filter(
  //         (item) => item.type === "7",
  //       )[0];
  //       // 家庭类型
  //       const homeStyleType = res.data.characterList.filter(
  //         (item) => item.type === "2",
  //       );
  //       // 分工情况
  //       // const parentingType = res.data.characterList.filter(
  //       //   (item) => item.type === "5",
  //       // )[0];
  //
  //       dialogData.currentDialogData.ageMsg =
  //         parentAgeMap.get(res?.data?.ageId ?? "") ?? "未知";
  //       dialogData.currentDialogData.statusMsg =
  //         UserStatusMap.get(dialogData.currentDialogData.status ?? "") ??
  //         "未知";
  //       dialogData.currentDialogData.registrationMethodMsg =
  //         UserRegistrationMethodMap.get(
  //           dialogData.currentDialogData.registrationMethod ?? "",
  //         ) ?? "未知";
  //       dialogData.currentDialogData.memberStatusMsg =
  //         UserMemberStatusMap.get(
  //           dialogData.currentDialogData.memberStatus ?? "",
  //         ) ?? "未知";
  //       if (familyCharacterType) {
  //         dialogData.currentDialogData.familyCharacterMsg =
  //           FamilyCharacterMap.get(familyCharacterType.id ?? "") ?? "未知";
  //       }
  //       if (parentIndustryType) {
  //         dialogData.currentDialogData.parentIndustryMsg =
  //           ParentIndustryMap.get(parentIndustryType.id ?? "") ?? "未知";
  //       }
  //       if (parentalEducationType) {
  //         dialogData.currentDialogData.parentalEducationMsg =
  //           ParentalEducationMap.get(parentalEducationType.id ?? "") ?? "未知";
  //       }
  //       if (childNumType) {
  //         dialogData.currentDialogData.childNumMsg =
  //           ChildNumMap.get(childNumType.id ?? "") ?? "未知";
  //       }
  //       if (homeStyleType) {
  //         dialogData.currentDialogData.homeStyleMsg = "";
  //         // const mock = [{ id: "11" }, { id: "19" }, { id: "15" }];
  //         homeStyleType.forEach((item: any, index: number) => {
  //           if (index === 0) {
  //             dialogData.currentDialogData.homeStyleMsg =
  //               HomeStyleMap.get(item.id ?? "") ?? "未知";
  //           } else {
  //             dialogData.currentDialogData.homeStyleMsg =
  //               dialogData.currentDialogData.homeStyleMsg +
  //                 "," +
  //                 HomeStyleMap.get(item.id ?? "") ?? "未知";
  //           }
  //         });
  //       }
  //       // if (parentingType) {
  //       //   dialogData.currentDialogData.parentingMsg =
  //       //     ParentingTypeMap.get(parentingType.id ?? "") ?? "未知";
  //       // }
  //     }
  //     if (res.data.children && res.data.children.length > 0) {
  //       res.data.children.forEach((item: any) => {
  //         if (item.orgList && item.orgList.length > 0) {
  //           item.orgList.forEach((subItem: any) => {
  //             if (subItem.type === "1") {
  //               item.schoolName = subItem.name;
  //             } else if (subItem.type === "2") {
  //               item.gradeName = subItem.name;
  //             } else {
  //               item.className = subItem.name;
  //             }
  //           });
  //         }
  //       });
  //     }
  //   }

  dialog.visible = true;
  dialogLoading.value = false;
  await getEvaluateList();
  // }
};

// 批准按钮
const handleAgree = async (row: any) => {
  // 禁用本行操作按钮，防止重复操作
  row.actionDisabled = true;
  loading.value = true;
  const [err, res] = await to(agreeApi(row.id));
  if (!err) {
    console.log(res);
    ElMessage({
      message: "操作成功",
      type: "success",
    });
    getJoinClassRequestList();
  } else {
    ElMessage({
      message: "操作失败",
      type: "error",
    });
    getJoinClassRequestList();
  }
  loading.value = false;
};

// 拒绝按钮
const handleDisagree = async (row: any) => {
  // 禁用本行操作按钮，防止重复操作
  row.actionDisabled = true;
  loading.value = true;
  const [err, res] = await to(disagreeApi(row.id));
  if (!err) {
    console.log(res);
    ElMessage({
      message: "操作成功",
      type: "success",
    });
    getJoinClassRequestList();
  } else {
    ElMessage({
      message: "操作失败",
      type: "error",
    });
    getJoinClassRequestList();
  }
  loading.value = false;
};

const currentChildList = ref([]);

const dialogLoading = ref(false);
// 重置用户名称
const handleResetName = async () => {
  dialogLoading.value = true;
  const [err] = await to(resetNameApi(currentUserId.value));
  if (!err) {
    ElMessage({
      message: "重置成功",
      type: "success",
    });
    await handleDetail(currentUserId.value);
  } else {
    ElMessage({
      message: "重置失败",
      type: "error",
    });
  }
};

// 重置小孩名称
const handleResetChildName = async (id: string) => {
  const [err] = await to(resetChildNameApi(id));
  if (!err) {
    ElMessage({
      message: "重置成功",
      type: "success",
    });
    await handleDetail(currentUserId.value);
  } else {
    ElMessage({
      message: "重置失败",
      type: "error",
    });
  }
};

const activeName = ref("1");
// 切换tab按钮
const handleTabClick = async (tab: TabsPaneContext) => {
  if (tab.props.name === "1") {
    // 评价
    activeName.value = "1";
    console.log(activeName.value);

    await getEvaluateList();
  } else if (tab.props.name === "2") {
    // 评论
    activeName.value = "2";
    console.log(activeName.value);

    await getCommentList();
  } else if (tab.props.name === "3") {
    // 日记
    activeName.value = "3";
    console.log(activeName.value);

    await getDiaryList();
  } else {
    // 笔记
    activeName.value = "4";
    console.log(activeName.value);

    await getNotesList();
  }
};
/**
 * 除了评论以外的隐藏
 * @param item 每个节点信息
 */
const handleHide = async (item: any) => {
  console.log(item, activeName.value);
  const [err, res] = await to(handleHideApi(item.id));
  if (!err) {
    console.log(res);
    ElMessage({
      type: "success",
      message: "隐藏成功！",
    });
    if (activeName.value === "1") {
      await getEvaluateList();
    } else if (activeName.value === "3") {
      await getDiaryList();
    } else {
      await getNotesList();
    }
  } else {
    ElMessage({
      type: "error",
      message: "隐藏失败！",
    });
  }
};
/**
 * 隐藏评论
 * @param item 每个节点信息
 */
const handleCommentHide = async (item: any) => {
  item.status = !item.status;
  const [err] = await to(handleCommentHideApi(item.status, item.id));
  if (!err) {
    ElMessage({
      type: "success",
      message: "隐藏成功！",
    });
    getCommentList();
  } else {
    ElMessage({
      type: "error",
      message: "隐藏失败！",
    });
    getCommentList();
  }
};

// 删除评论
const handleInnerDelete = async (item: any) => {
  if (activeName.value === "1") {
    const [err] = await to(deleteEvaluateApi(item.id));
    if (!err) {
      ElMessage({
        type: "success",
        message: "删除成功！",
      });
      await getEvaluateList();
    } else {
      ElMessage({
        type: "error",
        message: "删除失败！",
      });
      await getEvaluateList();
    }
  } else if (activeName.value === "2") {
    const [err] = await to(deleteCommentApi(item.id));
    if (!err) {
      ElMessage({
        type: "success",
        message: "删除成功！",
      });
      await getCommentList();
    } else {
      ElMessage({
        type: "error",
        message: "删除失败！",
      });
      await getCommentList();
    }
  } else if (activeName.value === "3") {
    const [err] = await to(deleteDiaryApi(item.id));
    if (!err) {
      ElMessage({
        type: "success",
        message: "删除成功！",
      });
      await getDiaryList();
    } else {
      ElMessage({
        type: "error",
        message: "删除失败！",
      });
      await getDiaryList();
    }
  } else {
    const [err] = await to(deleteNotesApi(item.id));
    if (!err) {
      ElMessage({
        type: "success",
        message: "删除成功！",
      });
      await getNotesList();
    } else {
      ElMessage({
        type: "error",
        message: "删除失败！",
      });
      await getNotesList();
    }
  }
};

const evaluateList = ref([]);
const evaluateTotal = ref(0);
// 获取用户评价列表
const getEvaluateList = async () => {
  getUserEvaluateParams.value.userId = currentUserId.value;
  const [err, res] = await to(getEvaluateListApi(getUserEvaluateParams.value));
  if (!err) {
    console.log(res);
    evaluateList.value = res.rows;
    evaluateTotal.value = Number(res.total);
  }
};

const commentList = ref([]);
const commentTotal = ref(0);
// 获取用户评论列表
const getCommentList = async () => {
  getCommentParams.value.userId = currentUserId.value;
  const [err, res] = await to(getCommentListApi(getCommentParams.value));
  if (!err) {
    console.log(res);

    commentList.value = res.rows ?? [];
    commentTotal.value = Number(res.total);
  }
};

const diaryList = ref([]);
const diaryTotal = ref(0);
// 获取用户日记列表
const getDiaryList = async () => {
  getDiaryParams.value.userId = currentUserId.value;
  const [err, res] = await to(getDiaryListApi(getDiaryParams.value));
  if (!err) {
    console.log(res);
    diaryList.value = res.rows ?? [];
    // diaryList.value.forEach((item: any) => {
    //   if (diaryList.value.ossList && diaryList.value.ossList.length > 0) {
    //   ossList.value = diaryList.value.ossList;
    // } else {
    //   ossList.value = []
    // }
    // })

    diaryTotal.value = Number(res.total);
  }
};
const notesList = ref([]);
const notesTotal = ref(0);
// 获取用户日记列表
const getNotesList = async () => {
  getNotesParams.value.userId = currentUserId.value;
  const [err, res] = await to(getNotesListApi(getNotesParams.value));
  if (!err) {
    console.log(res);
    notesList.value = res.rows ?? [];
    notesTotal.value = Number(res.total);
  }
};
/**
 * 提交按钮
 */
const addSubmit = () => {
  dialogFormRef.value.validate(async (valid: boolean) => {
    console.log(currentDialogData.value);

    if (valid) {
      if (currentDialogData.value.id) {
        // 编辑修改用户
        await updateClientUserApi(currentDialogData.value);
        ElMessage({
          message: "用户修改成功",
          type: "success",
        });
        getJoinClassRequestList();
      } else {
        await createClientUserApi(currentDialogData.value);
        currentDialogData.value = Object.assign({}, initAddUserBO);
        ElMessage({
          message: "用户添加成功",
          type: "success",
        });
        getJoinClassRequestList();
      }
      dialog.visible = false;
      await getJoinClassRequestList();
    }
  });
};

onMounted(() => {
  // getClientUserList();
  getOrganizationTree();
});
</script>

<style scoped lang="scss">
.el-date-pickerv {
  width: 900px;
}

.dialogForm {
  padding: 0 0 0 45px;

  // background-color: pink;
  .el-input {
    width: 219px;
  }

  .el-select {
    width: 219px;
  }
}

.dialogFooter {
  margin: 40px 0 0 450px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  .setting {
    margin-left: 100px;
  }
}

.scrollbar-flex-content {
  display: flex;
  /* width: 60%; */
}

.scrollbar-demo-item {
  flex-shrink: 0;
  border-radius: 4px;
}

img {
  flex: 1 0 33%; /* 这将使得每行中的图片数量尽可能保持为3个，但也会根据屏幕宽度进行调整 */
  margin: 10px; /* 调整间距 */
  max-width: 100%; /* 确保图片不会超出容器 */
}
</style>
